<?php

/**
 * This is the model class for table "bg_image".
 *
 * The followings are the available columns in table 'bg_image':
 * @property string $id
 * @property string $img_name
 * @property integer $status_id
 */
class BgImage extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return BgImage the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{bg_image}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('img_name', 'file',  'types'=>'jpg, png', 'on'=>'create'),
			array('img_name', 'file', 'allowEmpty'=>true, 'types'=>'jpg, png'),
			
			array('status_id', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, img_name, status_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		    'status'=>array(self::BELONGS_TO, 'StatusType', 'status_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'img_name' => '图片',
			'status_id' => '状态',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('img_name',$this->img_name,true);
		$criteria->compare('status_id',$this->status_id);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	/**
	 * 
	 * get random bg image name and return it as string
	 * @return string like xxxxx.png, png means transparent is needed.
	 */
	public function getRandomBgImg()
	{
	    //1 hours cache for BgImages
	    $cache = Yii::app()->cache;
	    $result = $cache->get('BgImages');
	    if ($result === false){
	        $result = BgImage::model()->findAll('status_id=1');
	        $cache->set('BgImages', $result, 60*60);
	    }
	    
	    $tmpInt = rand(0, count($result)-1);
	    return $result[$tmpInt]['img_name'];
	}
}